﻿using HCQ2_Common;
using HCQ2_Model;
using HCQ2_Model.ViewModel;
using HCQ2_Model.VR.Params;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace HCQ2UI_Logic
{
    /// <summary>
    ///  商品规格控制器
    /// </summary>
    public class VRSpecificationController : BaseLogic
    {
        //***************************1.0 规格管理*******************************
        #region 1.0 默认首次进入规格管理界面 + ActionResult DocList()
        /// <summary>
        ///  默认首次进入规格管理界面
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult SpecList()
        {
            ViewBag.fileId = RequestHelper.GetIntByName("fileId");
            return View();
        }
        #endregion

        #region 1.1 初始化Table + ActionResult InitTable()
        /// <summary>
        ///  初始化Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitTable()
        {
            int isMoney = RequestHelper.GetIntByName("isMoney"),//是否影响价格
                fileId = RequestHelper.GetIntByName("fileId");//商品id
            string isType = RequestHelper.GetDeStrByName("isType"),//类型
                specName = RequestHelper.GetDeStrByName("specName");//规格名称关键字
            var list = operateContext.bllSession.T_VRDDSpecMain.GetSpecResultList(fileId, isMoney, isType, specName);
            TableModel tModel = new TableModel()
            {
                total = list.Count,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 1.2 添加规格 + ActionResult AddSpec(VRSpecModel param)
        /// <summary>
        ///  添加规格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult AddSpec(VRSpecModel param)
        {
            List<string> urlList = new List<string>();
            try
            {           
                //处理规格
                var spec = param.toEntity();
                spec.userid = operateContext.Usr.user_guid;
                spec.user_id = operateContext.Usr.user_id;
                spec.createDate = DateTime.Now;
                spec.createName = operateContext.Usr.user_name;
                int mark = operateContext.bllSession.T_VRDDSpecMain.Add(spec);
                if(mark<=0)
                    return operateContext.RedirectAjax(1, "规格添加失败！", "", "");
                //处理图片附件
                if (spec.specType.Equals("图片"))
                {
                    //图片
                    var files = Request.Files;
                    //规格图片上传位置
                    string pathServer = "/uploadFile/VRSpecFile/" + operateContext.Usr.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                    string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
                    if (!Directory.Exists(uploadPath))
                        Directory.CreateDirectory(uploadPath);                  
                    for (int i = 0; i < files.Count; i++)
                    {
                        HttpPostedFileBase file = files[i];
                        if (null == file)
                            continue;
                        //1.上传文档
                        var fileUrl = "~" + pathServer + Helper.GetGuid + "." + file.FileName.Split('.')[1];
                        //1.上传文档
                        file.SaveAs(Server.MapPath(fileUrl));
                        urlList.Add(fileUrl);

                        var optionChild = new T_VRDDSpecChild
                        {
                            fileId = param.fileId,
                            specID = spec.specID,
                            optionName = param.optionList[i].optionName,
                            optionImage = fileUrl,
                            createDate=DateTime.Now
                        };
                        //添加子规格数据
                        operateContext.bllSession.T_VRDDSpecChild.Add(optionChild);  
                    }
                }
                else
                {
                    //文本
                    param.optionList.ForEach(s =>
                    {
                        var optionChild = new T_VRDDSpecChild
                        {
                            fileId = param.fileId,
                            specID = spec.specID,
                            optionName = s.optionName,
                            createDate = DateTime.Now
                        };
                        //添加子规格数据
                        operateContext.bllSession.T_VRDDSpecChild.Add(optionChild);
                    });
                }
                return operateContext.RedirectAjax(0, "规格添加成功~", "", "");
            }
            catch (Exception ex)
            {
                urlList?.ForEach(s =>
                {
                    if (!string.IsNullOrEmpty(s) && System.IO.File.Exists(Server.MapPath(s)))
                        System.IO.File.Delete(Server.MapPath(s));
                });              
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.3 编辑规格 + ActionResult EditSpec(VRSpecModel param)
        /// <summary>
        ///  编辑规格
        /// </summary>
        /// <param name="param">规格对象</param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult EditSpec(VRSpecModel param)
        {
            try
            {
                if(param.specID<=0)
                    return operateContext.RedirectAjax(1,"规格主键参数异常！", "", "");
                //if (!ModelState.IsValid)
                //    return operateContext.RedirectAjax(1, getErrorMessage(ModelState), "", "");
                //获取原始规格对象
                var obj = operateContext.bllSession.T_VRDDSpecMain.FindSingle(s => s.specID == param.specID);
                if(obj==null)
                    return operateContext.RedirectAjax(1, "待编辑的规格数据不存在！", "", "");
                var spec = param.toEntity();
                spec.updateDate = DateTime.Now;
                spec.updateId = operateContext.Usr.user_id;
                spec.updateName = operateContext.Usr.user_name;
                int mark = operateContext.bllSession.T_VRDDSpecMain.Modify(spec, s => s.specID == param.specID, "specName", "specMoney", "specType", "updateId", "updateName", "updateDate");
                if (mark <= 0)
                    return operateContext.RedirectAjax(1, "规格编辑失败！", "", "");
                //获取原始子规格列表
                var childList = operateContext.bllSession.T_VRDDSpecChild.Select(s => s.specID == param.specID);
                List<string> sb = new List<string>();
                //处理图片附件
                if (spec.specType.Equals("图片"))
                {
                    //规格图片上传位置
                    string pathServer = "/uploadFile/VRSpecFile/" + operateContext.Usr.user_guid + "/" + DateTime.Now.ToString("yyyyMMdd") + "/";
                    string uploadPath = request.MapPath(request.ApplicationPath + pathServer);
                    if (!Directory.Exists(uploadPath))
                        Directory.CreateDirectory(uploadPath);
                    param.optionList.ForEach(o =>
                    {
                        if (o.optionID > 0)
                            sb.Add(o.optionID.ToString());
                        var temp = childList.Where(s => s.optionID == o.optionID)?.FirstOrDefault();
                        var file = Request.Files[o.imageCode];
                        if (temp != null)
                        {
                            //编辑
                            string imageUrl = temp.optionImage;
                            if (o.isEdit > 0 && file!=null)
                            {
                                //删除原始图片
                                if (!string.IsNullOrEmpty(temp.optionImage) && System.IO.File.Exists(Server.MapPath(temp.optionImage)))
                                    System.IO.File.Delete(Server.MapPath(temp.optionImage));
                                //更新图片
                                //1.上传文档
                                var fileUrl = "~" + pathServer + Helper.GetGuid + "." + file.FileName.Split('.')[1];
                                //1.上传文档
                                file.SaveAs(Server.MapPath(fileUrl));
                                imageUrl = fileUrl;
                            }
                            operateContext.bllSession.T_VRDDSpecChild.Modify(new T_VRDDSpecChild
                            {
                                optionName = o.optionName,
                                optionImage = imageUrl,
                                updateDate = DateTime.Now
                            }, s => s.optionID == o.optionID, "optionName", "optionImage", "updateDate");
                        }
                        else
                        {
                            //新增
                            if (file != null)
                            {
                                //更新图片
                                //1.上传文档
                                var fileUrl = "~" + pathServer + Helper.GetGuid + "." + file.FileName.Split('.')[1];
                                //1.上传文档
                                file.SaveAs(Server.MapPath(fileUrl));
                                operateContext.bllSession.T_VRDDSpecChild.Add(new T_VRDDSpecChild
                                {
                                    fileId = obj.fileId,
                                    specID = obj.specID,
                                    optionName = o.optionName,
                                    optionImage = fileUrl,
                                    createDate = DateTime.Now
                                });
                            }
                        }
                    });
                }
                else
                {
                    //文本
                    param.optionList.ForEach(o =>
                    {
                        if (o.optionID > 0)
                            sb.Add(o.optionID.ToString());
                        var temp = childList.Where(s => s.optionID == o.optionID)?.FirstOrDefault();
                        if (temp != null)
                        {
                            //编辑
                            //删除原始图片
                            if (!string.IsNullOrEmpty(temp.optionImage) && System.IO.File.Exists(Server.MapPath(temp.optionImage)))
                                System.IO.File.Delete(Server.MapPath(temp.optionImage));
                            operateContext.bllSession.T_VRDDSpecChild.Modify(new T_VRDDSpecChild
                            {
                                optionName = o.optionName,
                                optionImage = "",
                                updateDate = DateTime.Now
                            }, s => s.optionID == o.optionID, "optionName", "optionImage", "updateDate");
                        }
                        else
                        {
                            //新增
                            var child = new T_VRDDSpecChild
                            {
                                fileId = obj.fileId,
                                specID = obj.specID,
                                optionName = o.optionName,
                                optionImage = "",
                                createDate = DateTime.Now
                            };
                            int c = operateContext.bllSession.T_VRDDSpecChild.Add(child);
                            if(c>0)
                                sb.Add(child.optionID.ToString());
                        }
                    });
                }
                //获取待删除记录附件地址列表【删除图片附件】
                List<string> picList = operateContext.bllSession.T_VRDDSpecMain.GetDeleteSpecChildPic(sb, obj.specID);
                if(picList!=null && picList.Count >0)
                {
                    picList.ForEach(o =>
                    {
                        if (!string.IsNullOrEmpty(o) && System.IO.File.Exists(Server.MapPath(o)))
                            System.IO.File.Delete(Server.MapPath(o));
                    });
                }
                //删除已经不存在的记录【删除数据库记录】
                if(sb!=null && sb.Count>0)
                    operateContext.bllSession.T_VRDDSpecMain.DeleteSpecChild(sb, obj.specID);
                return operateContext.RedirectAjax(0, "规格编辑成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.4 删除规格 +ActionResult DelSpecById(int id)
        /// <summary>
        ///  删除规格
        /// </summary>
        /// <param name="id">规格主表id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DelSpecById(int id)
        {
            try
            {
                if (id<=0)
                    return operateContext.RedirectAjax(1, "需要删除的规格参数必填~", "", "");
                var obj = operateContext.bllSession.T_VRDDSpecMain.FindSingle(s => s.specID == id);
                if (obj==null)
                    return operateContext.RedirectAjax(1, "需要删除的规格不存在或者已经删除~", "", "");
                //根据规格获取子规格
                var optionList = operateContext.bllSession.T_VRDDSpecChild.Select(s => s.specID == id);
                //1、删除主表
                operateContext.bllSession.T_VRDDSpecMain.Delete(s => s.specID == id);
                //2、删除规格组合表
                operateContext.bllSession.T_VRDDSpecGroup.Delete(s => s.fileId == obj.fileId);
                //3、删除库存表
                operateContext.bllSession.T_VRDDSpecRepertory.Delete(s => s.fileId == obj.fileId);
                //4、删除价格表
                operateContext.bllSession.T_VRDDSpecPrice.Delete(s => s.fileId == obj.fileId);
                //5、删除子表图片附件
                optionList.ForEach(s =>
                {
                    if (!string.IsNullOrEmpty(s.optionImage) && System.IO.File.Exists(Server.MapPath(s.optionImage)))
                        System.IO.File.Delete(Server.MapPath(s.optionImage));
                });
                //6、删除子表
                operateContext.bllSession.T_VRDDSpecChild.Delete(s => s.specID == id);
                return operateContext.RedirectAjax(0, "数据删除成功~", "", "");
            }
            catch (Exception ex)
            {
                return operateContext.RedirectAjax(1, ex.Message, "", "");
            }
        }
        #endregion

        #region 1.5 更新规格组合、库存、价格列表 +ActionResult UpdateSpecGroup(int id)
        /// <summary>
        ///  更新规格组合、库存、价格列表
        /// </summary>
        /// <param name="id">商品id</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UpdateSpecGroup(int id)
        {
            if (id <= 0)
                return operateContext.RedirectAjax(1, "需要更新的规格参数必填~", "", "");
            bool mark = operateContext.bllSession.T_VRDDSpecMain.ResetSpecChildOption(id);
            if(mark)
                return operateContext.RedirectAjax(0, "数据重置成功~", "", "");
            return operateContext.RedirectAjax(1, "数据重置失败~", "", "");
        }
        #endregion

        //***************************2.0 库存管理*******************************
        #region 2.0 默认首次进入库存管理界面 + ActionResult RepertoryList()
        /// <summary>
        ///  默认首次进入库存管理界面
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult RepertoryList()
        {
            return View();
        }
        #endregion

        #region 2.1 初始化库存Table + ActionResult InitRepertoryTable()
        /// <summary>
        ///  初始化库存Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitRepertoryTable()
        {
            int fileId = RequestHelper.GetIntByName("fileId");//商品id
            var list = operateContext.bllSession.T_VRDDSpecMain.GetSpecRepertoryList(fileId);
            TableModel tModel = new TableModel()
            {
                total = list.Count,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 2.2 单个或批量编辑库存 +ActionResult BatchRepertoryEdit()
        /// <summary>
        ///  单个或批量编辑库存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchRepertoryEdit(List<SpecRepertoryModel> param)
        {
            param.ForEach(s => operateContext.bllSession.T_VRDDSpecRepertory.Modify(new T_VRDDSpecRepertory { quantity = s.quantity }, o => o.keyCode.Equals(s.keyCode), "quantity"));
            return operateContext.RedirectAjax(0, "库存更新成功~", "", "");
        }
        #endregion

        //***************************3.0 价格管理*******************************
        #region 3.0 默认首次进入价格管理界面 + ActionResult PriceList()
        /// <summary>
        ///  默认首次进入价格管理界面
        /// </summary>
        /// <returns></returns>
        [HCQ2_Common.Attributes.Load]
        [HCQ2_Common.Attributes.Element]
        [HttpGet]
        public ActionResult PriceList()
        {
            return View();
        }
        #endregion

        #region 3.1 初始化价格Table + ActionResult InitPriceTable()
        /// <summary>
        ///  初始化价格Table
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult InitPriceTable()
        {
            int fileId = RequestHelper.GetIntByName("fileId");//商品id
            var list = operateContext.bllSession.T_VRDDSpecMain.GetSpecPriceList(fileId);
            TableModel tModel = new TableModel()
            {
                total = list.Count,
                rows = list
            };
            return Json(tModel, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 3.2 单个或批量编辑价格 +ActionResult BatchPriceEdit(List<SpecPriceModel> param)
        /// <summary>
        ///  单个或批量编辑价格
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult BatchPriceEdit(List<SpecPriceModel> param)
        {
            param.ForEach(s => operateContext.bllSession.T_VRDDSpecPrice.Modify(new T_VRDDSpecPrice { specMoney = s.specMoney }, o => o.keyCode.Equals(s.keyCode), "specMoney"));
            return operateContext.RedirectAjax(0, "价格更新成功~", "", "");
        }
        #endregion
    }
}